﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Artech.PetShop.Orders;
using Artech.PetShop.Common;
using Artech.PetShop.Orders.BusinessEntity;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace PetShop
{
    public partial class ShoppingCart : ViewBase<OrderPresenter>, IOrderView
    {
        public ShoppingCart()
        {
            this.Presenter = new OrderPresenter(this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack)
            {
                return;
            }
            this.Presenter.ShowOrderInfo();
        }

        #region IOrderView Members

        public void BindingOrderInfo(Order order)
        {
            this.GridViewOrder.DataSource = order.Details;
            this.GridViewOrder.DataBind();
            this.LabelTotalPrice.Text = order.TotalPrice.ToString();
            this.LabelQuantity.Text = order.Details.Sum(item => item.Quantity).ToString();
        }

        #endregion

        protected void GridViewOrder_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "DeleteProduct":
                        {
                            Label productIDLabel = (Label)this.GridViewOrder.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("LabelProductID");
                            Guid prodyctID = new Guid(productIDLabel.Text);
                            this.Presenter.RemoveProductFromShippingCart(prodyctID);
                            break;
                        }
                    case "UpdateQuantity":
                        {
                            Label productIDLabel = (Label)this.GridViewOrder.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("LabelProductID");
                            Guid prodyctID = new Guid(productIDLabel.Text);
                            TextBox quantityTextBox = (TextBox)this.GridViewOrder.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("TextBoxQuantity");
                            int quantity = int.Parse(quantityTextBox.Text);
                            this.Presenter.UpdateQuantity(prodyctID, quantity);
                            break;
                        }
                }
            }
            catch (Exception ex)
            {
                if (ExceptionPolicy.HandleException(ex, "webClientPolicy"))
                {
                    throw;
                }
            }
        }

        protected void LinkButtonCheckout_Click(object sender, EventArgs e)
        {
            this.Presenter.Submit();
        }
    }
}
